package com.neusoft.ecommerce.controller;

import com.neusoft.ecommerce.entity.Manager;
import com.neusoft.ecommerce.service.ManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * @author 紫煦桉
 */
@RestController
public class LoginController {

    private final ManagerService managerService;
    private final Logger logger = LoggerFactory.getLogger(LoggerFactory.class);

    public LoginController(ManagerService managerService) {
        this.managerService = managerService;
    }

    @GetMapping("/login_page")
    public ModelAndView loginPage() {
        return new ModelAndView("login");
    }

    @PostMapping("/login")
    public Map login(Manager manager, HttpSession session) {
        System.out.println(manager.getManagerName() + " " + manager.getManagerPassword());
        Map<String, Object> map = new HashMap<>(16);
        Manager message = managerService.login(manager);
        logger.info(String.valueOf(message));
        if (message != null) {
            session.setAttribute("Manager_Name", message);
            map.put("msg", "ok");
            map.put("code", 0);
        } else {
            map.put("msg", "账号或密码有误");
            map.put("code", 1);
        }
        return map;
    }

    @GetMapping("/index_page")
    public ModelAndView indexPage() {
        return new ModelAndView("index");
    }

    @GetMapping("/register_page")
    public ModelAndView registerPage() {
        return new ModelAndView("register");
    }

    @PostMapping("/checkManagerName")
    public Map checkManagerName(Manager manager) {
        System.out.println(manager);
        Map<String, Object> map = new HashMap<>(16);
        Manager message = managerService.findManagerName(manager);
        System.out.println(message);
        if (message != null) {
            map.put("msg", "ok");
            map.put("code", 1);
        } else {
            map.put("msg", "用户名已存在");
            map.put("code", 0);
        }
        return map;
    }

    @PostMapping("/register")
    public Map register(Manager manager) {
        System.out.println(manager);
        System.out.println(manager.getManagerName() + " " + manager.getManagerPassword());
        Map<String, Object> map = new HashMap<>(16);
        if (managerService.add(manager)) {
            map.put("msg", "ok");
            map.put("code", 0);
        } else {
            map.put("msg", "错误.");
            map.put("code", 1);
        }
        return map;
    }

}
